# Title     : TODO
# Objective : TODO
# Created by: xueyj
# Created on: 2020/9/28
pacman::p_load(reshape2, magrittr, dplyr, sqldf, timeDate, lazyopt, chron)

opt <- matrix(c(
  "inputfile", "i", 2, "character", "Set the input file path", " ",
  "groupfile", "g", 1, "character", "Sets the packet file path", "",
  "choose_unit", "cu", 1, "character", "", " ",
  "outputpackage", "o", 2, "character", "Set the output folder path", " "
), byrow = TRUE, ncol = 6) %>% lazyopt(arg <- c("-i", "E:/projects/Lysimeter_Systems/src/data/Input.csv",
                                                "-o", "E:/projects/Lysimeter_Systems/src/output"))

correctTime <- function(testData) {

  checkTime <- function(a) {
    k <- 3 - (a %>% lazyopt::fenge() %>% length())
    if (k < 0) { errorCondition("Wrong time format") }
    if (k == 0) { return(a) }
    if (k > 0) {
      return(a %>% paste0(rep(":00", k)))
    }
  }

  for (i in seq_len(nrow(testData))) {
    testData[, 1] <- testData[, 1] %>% as.character()
    a <- testData[i, 1] %>%
      as.character() %>%
      lazyopt::fenge(" ")
    a[1] <- as.Date(a[1]) %>% as.character()
    a[2] <- checkTime(a[2]) %>%
      as.character() %>%
      as.times() %>%
      as.character()
    testData[i, 1] <- paste(a[1], a[2])
  }
  return(testData)
}

choseTimeArea <- function(testData, minTime, maxTime) {
  index <- NULL
  minTime %<>% timeDate()
  maxTime %<>% timeDate()
  for (i in seq_len(nrow(testData))) {
    a <- testData[i, 1] %>% as.character() %>% timeDate()
    if (a <= maxTime && a >= minTime) {
      index[i] <- 1
    }else {
      index[i] <- 0
    }
  }
  return(which(index == 1))
}

get_unit <- function(choseUnit, firstData) {
  dd <- colnames(firstData)[3:ncol(firstData)]
  if (choseUnit %in% dd) {
    firstData %>%
      select(Time, Sensor, choseUnit) %>%
      dcast(Time ~ Sensor) %>%
      return()
  }else {
    return(-1)
  }
}


rawData <- opt %$%
  read.csv(inputfile)

dd <- colnames(rawData)[3:ncol(rawData)]
print("you can choose some units to write table,if you want to choose all,you can input string 'all'")
cat("units: "); cat(dd)
zz <- scan(what = character(), nmax = length(dd))
if (zz != "all") { dd <- zz }

for (i in seq_along(dd)) {
  choseUnit <- dd[i]
  unitData <- rawData %>% get_unit(choseUnit, .)
  if (unitData == -1) { print(paste0(choseUnit, " is no exist")); next }
  print(paste0("start:", choseUnit))
  #算饱和蒸汽压差（VPD） unitData[, 4]Rh    unitData[, 6]TEMP/2/VP4
  vpd <- (1 - unitData[, 4] / 100) *
    0.6112 *
    exp((17.67 * unitData[, 6]) / (243.5 + unitData[, 6]))
  unitData %<>% mutate(vpd = vpd)
  #算各单元土壤体积水（VWC） unitData[, 3]DIELEC
  vwc <- 4.3 * (10^-6) * (unitData[, 3]^3) - 5.5 * (10^-4) * (unitData[, 3]^2) + 2.92 * (10^-2) * unitData[, 3] - 5.3 * (10^-2)
  unitData %<>% mutate(vwc = vwc)
  write.table(unitData, file = paste0(opt$outputpackage, "/", choseUnit, ".", "xls"), sep = "\t", col.names = NA)
  print(paste0(paste0(opt$outputpackage, "/", choseUnit, ".", "xls"), " | output success"))
}
















